package com.yaoxun.gateway.util;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.yaoxun.gateway.exception.JsonException;

public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER;
    
    static {
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
        OBJECT_MAPPER = new ObjectMapper()
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
                .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT)
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .setTimeZone(timeZone)
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }
    
    
    public static ObjectMapper getMapper() {
        return OBJECT_MAPPER;
    }
    
    
    public static String toJsonString(Object obj) {
        try {
            return getMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
        	throw new JsonException(e);
        }
    }
    
    
    public static <T> T parse(String content, Class<T> valueType) {
        try {
            return getMapper().readValue(content, valueType);
        } catch (JsonProcessingException e) {
        	throw new JsonException(e);
        }
    }
    
    
}
